<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;

use app\index\model\User as UserModel;

class Pingjiao extends Controller
{
	public function index(Request $request){
		// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		
		// 获取参数仅包含数组中字段
        $data = $request->only(['tid']);
		if ($data == null) {
            return json(['success'=>false, "msg"=>'喔豁，参数错误了']);
        }
		
		 // 查询所有老师关联信息
        $getCCTSql = "
        	SELECT 
				DISTINCT(course.`name`) as 'coursename',
				course.`id` as 'courseid',
				course.courseimg AS 'courseimg',
				course.note AS 'coursenote',
				teacher.`id` AS 'teacherid',
				teacher.`name` AS 'teachername',
				teacher.`sex` AS 'teachersex',
				teacher.`note` AS 'teachernote'
			FROM((
					oes_emp teacher  LEFT JOIN  oes_dept dept ON teacher.dept_id = dept.id
				)	LEFT JOIN oes_clazzcourseteacher ccse ON ccse.teacher_id = teacher.id
				) LEFT JOIN oes_course course ON course.id = ccse.course_id
			WHERE teacher.`status` = 1 AND teacher.`id` = ?
        	";
		if($indexUserInfo['type'] == 2){

	        // 查询班级、课程、老师关联信息
        	$getCCTSql = "
	        	SELECT 
					class.`name` AS 'classname',
					class.`id` AS 'classid',
					course.`name` as 'coursename',
					course.`id` as 'courseid',
					course.courseimg AS 'courseimg',
					course.note AS 'coursenote',
					teacher.`id` AS 'teacherid',
					teacher.`name` AS 'teachername',
					teacher.`sex` AS 'teachersex',
					teacher.`note` AS 'teachernote'
				FROM(((
					  oes_clazzcourseteacher ccse LEFT JOIN oes_clazz class ON class.id = ccse.clazz_id
					) LEFT JOIN oes_course course ON course.id = ccse.course_id
					) LEFT JOIN oes_emp teacher ON teacher.id = ccse.teacher_id
					) LEFT JOIN oes_student student ON student.clazz_id = ccse.clazz_id
					  WHERE teacher.`status` = 1 AND class.`code` = ? AND student.sysuser_id = ? AND teacher.`id` = ?
	        	";
		}

		//查询某个老师被评人次数
		$getPJCountSql = "
			SELECT
				COUNT(erecord.id) AS 'count'
			FROM oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE erecord.teacher_id = ? AND erecord.etask_id = ?
			";
			
		//查询评教任务
		$getEtaskSql = "
			SELECT 
				*
			FROM 
				oes_etask
			WHERE 
				end_data > date_format(now(),'%y-%m-%d') AND status = 1
		";
		
		//查询用户角色，根据角色分配评教类型
		$userRoleSql = "
			SELECT 
				role.`name`
			FROM user_role LEFT JOIN role on user_role.rid = role.id where user_role.uid = ?
		";
		
		//
		if($indexUserInfo['type'] == 2){
			  $getCCT = Db::query($getCCTSql, [$indexUserInfo['classcode'],$indexUserInfo['sysuser_id'],$data['tid']]);
		}else{
			 $getCCT = Db::query($getCCTSql, [$data['tid']]);
			 $userRole = Db::query($userRoleSql, [$indexUserInfo['sysuser_id']]);
			 //dump($userRole);
			 $this->assign("userRole", $userRole[0]);
		}
       
		$getEtask = Db::query($getEtaskSql);
		
		foreach ($getCCT as &$item) {
           //dump($getCCT);
           $getPJCount = Db::query($getPJCountSql,[$item['teacherid'],$getEtask[0]['id']]);
           //dump($getPJCount);
           $item['getPJCount'] = $getPJCount[0]['count'];
           $item['startData'] = $getEtask[0]['start_data'];
           $item['endData'] = $getEtask[0]['end_data'];
           $item['etask_id'] = $getEtask[0]['id'];
           $item['classid'] = '4';
        }
        
			$stateWhere['euser_id'] = $indexUserInfo['sysuser_id'];
	        $stateWhere['teacher_id'] = $data['tid'];
	        $stateWhere['etask_id'] = $getEtask[0]['id'];
		if($indexUserInfo['type'] == 2){
			$stateWhere['etype_id'] = 1;
	        $state = Db::table('oes_erecordnew')->where($stateWhere)->find();
			$this->assign("state", count($state));
		}else{
			$this->assign("tid", $data['tid']);
			//教师自评
			if($indexUserInfo['id'] == $data['tid']){
				$stateWhere['etype_id'] = 2;
				$jszp = Db::table('oes_erecordnew')->where($stateWhere)->find();
				$this->assign("jszp", count($jszp));
			}
			
			//同行评教
			$stateWhere['etype_id'] = 3;
			$thpj = Db::table('oes_erecordnew')->where($stateWhere)->find();
			$this->assign("thpj", count($thpj));
			$userRoles = Db::query($userRoleSql, [$indexUserInfo['sysuser_id']]);
			if($userRoles[0]['name'] == "教研室领导"){
				$stateWhere['etype_id'] = 4;
				$jyld = Db::table('oes_erecordnew')->where($stateWhere)->find();
				$this->assign("jyld", count($jyld));
			}
			
			if($userRoles[0]['name'] == "系部领导"){
				$stateWhere['etype_id'] = 5;
				$xbld = Db::table('oes_erecordnew')->where($stateWhere)->find();
				$this->assign("xbld", count($xbld));
			}
		}
		
		$this->assign("info", $getCCT[0]);
		$this->assign("title", "预评教");
		return $this->fetch();  
	}   
	
	/**
	 * 获取一个评教预览数据
	 */
    public function pingJiaoInfo(Request $request)
    {
    	// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		
		 // 获取参数仅包含数组中字段
        $data = $request->only(['tid']);
		if ($data == null) {
            return json(['success'=>false, "msg"=>'喔豁，参数错误了']);
        }
		
		 // 查询所有老师关联信息
        $getCCTSql = "
        	SELECT 
			DISTINCT(course.`name`) as 'coursename',
			course.courseimg AS 'courseimg',
			course.note AS 'coursenote',
			teacher.`id` AS 'teacherid',
			teacher.`name` AS 'teachername',
			teacher.`sex` AS 'teachersex',
			teacher.`note` AS 'teachernote'
			FROM((
				oes_emp teacher  LEFT JOIN  oes_dept dept ON teacher.dept_id = dept.id
			)	LEFT JOIN oes_clazzcourseteacher ccse ON ccse.teacher_id = teacher.id
			) LEFT JOIN oes_course course ON course.id = ccse.course_id
			WHERE teacher.`status` = 1 AND teacher.`id` = ?
        	";
		if($indexUserInfo['type'] == 2){
			// 查询班级、课程、老师关联信息
	        $getCCTSql = "
	        	SELECT 
					class.`name` AS 'classname',
					course.`name` as 'coursename',
					course.courseimg AS 'courseimg',
					course.note AS 'coursenote',
					teacher.`id` AS 'teacherid',
					teacher.`name` AS 'teachername',
					teacher.`sex` AS 'teachersex',
					teacher.`note` AS 'teachernote'
				FROM(((
					  oes_clazzcourseteacher ccse LEFT JOIN oes_clazz class ON class.id = ccse.clazz_id
					) LEFT JOIN oes_course course ON course.id = ccse.course_id
					) LEFT JOIN oes_emp teacher ON teacher.id = ccse.teacher_id
					) LEFT JOIN oes_student student ON student.clazz_id = ccse.clazz_id
					  WHERE teacher.`status` = 1 AND class.`code` = ? AND student.sysuser_id = ? AND teacher.`id` = ?
	        	";
		}
      
		//查询某个老师被评人次数
		$getPJCountSql = "
			SELECT
				COUNT(erecord.id) AS 'count'
			FROM oes_erecordnew erecord LEFT JOIN oes_etask etask ON etask.id = erecord.etask_id
				WHERE erecord.teacher_id = ? AND erecord.etask_id = ?
			";
			
		$getEtaskSql = "
			SELECT 
				*
			FROM 
				oes_etask
			WHERE 
				end_data > date_format(now(),'%y-%m-%d') AND status = 1
		";
		
		if($indexUserInfo['type'] == 2){
			 $getCCT = Db::query($getCCTSql, [$indexUserInfo['classcode'],$indexUserInfo['sysuser_id'],$data['tid']]);
		}else{
			 $getCCT = Db::query($getCCTSql, [$data['tid']]);
		}
       
		$getEtask = Db::query($getEtaskSql);
		
		if(count($getCCT) > 0 ){
			foreach ($getCCT as &$item) {
	            // $SubMenu = Db::query($subMenuSql, [2, $item]);
	            // dump($item['id']);
	           $getPJCount = Db::query($getPJCountSql,[$item['teacherid'],$getEtask[0]['id']]);
	           $item['getPJCount'] = $getPJCount[0]['count'];
	           $item['startData'] = $getEtask[0]['start_data'];
	           $item['endData'] = $getEtask[0]['end_data'];
	        }
	        return json(['success'=>true, "msg"=>'OK','obj'=>$getCCT]);
		}else{
			return json(['success'=>false, "msg"=>'喔豁，没数据哟']);
		}
		
		
	/*	dump($getEtask);
		dump($getCCT);*/
        //$this->assign("list", $getCCT);	
		//dump(json(['success'=>true, "msg"=>'OK','obj'=>$getCCT]));
		
         	
    }
    
    
  /**
	 * 计算一个备选项的权重总分(递归算法)
	 */
    public function suanfen($normtarget){
    	//echo "<pre>";
		function t($arr,$pid=0,$lev=0,$fenshu=1){
			//print_r($arr);
			static $list = array();
			foreach($arr as $v){
				if($v['parentnormtarget_id']==$pid){
					$v['fenshu'] = ($fenshu * $v['entropy']);
					//echo str_repeat(" ",$lev).$v['name']."<br />";
					//这里输出，是为了看效果
					$list[] = $v;
					t($arr,$v['id'],$lev+1,$v['fenshu']);
				}
				
			}
			return $list;
		}
		//print_r($normtarget);
		//echo "<hr >";
		//print_r($list);
		return t($normtarget);
    }
    
   	//评教页面跳转控制器
	public  function pingjiaopage(){
		// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		
		
		//根据评教类型查询指标
		$normtargetWhere['etype_id']=$_GET['etypeid'];//学生评教
	  	$normtarget = Db::table('oes_normtarget')->where($normtargetWhere)->select();
		foreach ($normtarget as $key=>$value){
		  if (empty($value['parentnormtarget_id']))
		    //unset($normtarget[$key]);//删除下标为$key的数组值
		  	$normtarget[$key]['entropy'] = 1;//设置顶级指标权重为1
		}
		$list = $this->suanfen($normtarget);
	 	//print_r($list);
		foreach ($list as &$item) {
			//查询备选项
			$item['normitem'] = [];
			$normitem = Db::table('oes_normitem')->where('normtarget_id = '.$item['id'])->select();
			if(count($normitem) > 0 ){
				/*print_r($normitem);
				print_r("---------------------------");*/
				foreach ($normitem as &$item1) {
					$item1['score'] = $item1['score'] * $item['fenshu'];
					
				}
				$item['normitem'] = $normitem;
			}else{
				$this->assign("msg", "暂无评教数据");	
			}
			
		}
		
		foreach ($list as $key=>$value)
		{
		  if (empty($value['parentnormtarget_id']))
		    unset($list[$key]);
		}
		sort($list);
		
		//print_r($list);
		$this->assign("list", $list);
		if(Session::get('indexUserInfo')['type'] == 2){
			$this->assign("title", "学生评教");		
		}else{
			$this->assign("title", "教师评教");//教师评教将根据教师权限来设置title
		}
		
		return $this->fetch();
	
	}

	/**
	 * 提交评教结果
	 */
	public function dopingjiaopost(Request $request){
		// 获取用户信息 $indexUserInfo['indexUserInfo']
        $indexUserInfo = Session::get('indexUserInfo');
        if ($indexUserInfo == null) {
            $this->redirect('/index/index/login.html');
        }
		
		// 获取前端传的参数
        $data = $request->param();
		if ($data == null) {
            return json(['success'=>false, "msg"=>'修改资料填写有误']);
        }
		
		$data['euser_id'] = $indexUserInfo['sysuser_id'];
		
		$data['addtime'] = date('y-m-d h:i:s',time());
		
		$result = Db::table('oes_erecordnew')->insert($data);
		
		if($result > 0){
			$indexUserInfo['usererecord'] = $indexUserInfo['usererecord'] + 1;
			if($indexUserInfo['type'] != 2){
				$indexUserInfo['userberecord'] = $indexUserInfo['userberecord'] + 1;
			}
			
			Session::set('indexUserInfo', $indexUserInfo);
			return json([
			'success'=>true, 
			'msg'=>'<span style="font-size: 2rem;display: block;padding: 2px 0;">评教提交成功</br>感谢你真诚的评教！</span>',
			'obj'=>'/index/index.html']);
        } else {
            return json([
            'success'=>false,
            'msg'=>'<span style="font-size: 2rem;display: block;padding: 2px 0;">当前网络不稳</br>评教信息提交失败了</br>请重新评教！</span>']);
        }
		
	}
	
}
